<?php
namespace Home\Controller;
use Think\Controller;
class CartController extends Controller 
{
    public function add()
    {
        $memberId = session('m_id');
        if(!$memberId){
            session('returnUrl',U('Index/index'));
            redirect(U('Member/login'));
        }

    	if(IS_POST)
    	{
    		$cartModel = D('Cart');
    		if($cartModel->create(I('post.'), 1))
    		{
    			if($cartModel->add())
    			{
    				$this->success('添加成功！', U('lst'));
    				exit;
    			}
    		}
    		$this->error('添加失败 '.$cartModel->getError());
    	}

		// 设置页面中的信息
		$this->assign(array(
			'_page_title' => '添加',
			'_page_btn_name' => '列表',
			'_page_btn_link' => U('lst'),
		));
		$this->display();
    }
    public function edit()
    {
    	$id = I('get.id');
    	if(IS_POST)
    	{
    		$model = D('Cart');
    		if($model->create(I('post.'), 2))
    		{
    			if($model->save() !== FALSE)
    			{
    				$this->success('修改成功！', U('lst', array('p' => I('get.p', 1))));
    				exit;
    			}
    		}
    		$this->error($model->getError());
    	}
    	$model = M('Cart');
    	$data = $model->find($id);
    	$this->assign('data', $data);

		// 设置页面中的信息
		$this->assign(array(
			'_page_title' => '修改',
			'_page_btn_name' => '列表',
			'_page_btn_link' => U('lst'),
		));
		$this->display();
    }
    public function delete()
    {
    	$model = D('Cart');
    	if($model->delete(I('get.id', 0)) !== FALSE)
    	{
    		$this->success('删除成功！', U('lst', array('p' => I('get.p', 1))));
    		exit;
    	}
    	else 
    	{
    		$this->error($model->getError());
    	}
    }
    public function lst()
    {
        $memberId = session('m_id');
        if(!$memberId){
            session('returnUrl',U('Cart/lst'));
            redirect(U('Member/login'));
        }

    	$cartModel = D('Cart');
    	$data = $cartModel->cartList();
		// 设置页面中的信息
		$this->assign(array(
		    'data' => $data,
            '_page_title' => '购物车详情页',
            '_page_keywords' => '购物车详情页',
            '_page_description' => '购物车详情页',
		));
    	$this->display();
    }

    public function ajaxCartList(){
        $cartModel = D('Home/Cart');
        $data = $cartModel->cartList();
        echo json_encode($data);
    }

    public function update_cart(){
        if(IS_POST || true){
            $cartModel = D("Cart");
            if($cartModel->updateGoodsNumber(I('post.goods_number'))){
                $this->success('数量更新成功！');
                exit;
            }
            $this->error('更新失败，'.$cartModel->getError());
        }
    }
}